package com.enterprise.support.utility;


import javax.mail.internet.MimeUtility;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午10:36
 * Email: z82422@gmail.com
 * 大杂烩，一堆 辅助函数
 */
public class Function implements Serializable {

    public static String getBase64(String encodeStr) throws Exception {
        try {
            encodeStr = encodeStr.substring(encodeStr.length() / 2, encodeStr.length()) + encodeStr.substring(0, encodeStr.length() / 2);
            encodeStr = encodeStr.substring(encodeStr.length() - 1, encodeStr.length()) + encodeStr.substring(1, encodeStr.length() - 1) + encodeStr.substring(0, 1);
            BufferedReader reader = new BufferedReader(new InputStreamReader(MimeUtility.decode(new ByteArrayInputStream(encodeStr.getBytes()), "base64")));
            return reader.readLine();
        } catch (Exception ex) {
            throw new Exception(ex);
        }
    }


    public static String toBase64(String decodeStr) {
        return toBase64(decodeStr, false);
    }


    public static String toBase64(String decodeStr, boolean space) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] in = decodeStr.getBytes();
            ByteArrayOutputStream inStream = new ByteArrayOutputStream();
            inStream.write(in, 0, in.length);
            //补0
            if ((in.length % 3) == 1) {
                inStream.write(0);
                inStream.write(0);
            } else if ((in.length % 3) == 2) {
                inStream.write(0);
            }
            inStream.writeTo(MimeUtility.encode(out, "base64"));
            decodeStr = !space ? out.toString() : out.toString().replaceAll("(\n|\r)", "");
            decodeStr = decodeStr.substring(decodeStr.length() - 1, decodeStr.length()) + decodeStr.substring(1, decodeStr.length() - 1) + decodeStr.substring(0, 1);
            decodeStr = decodeStr.substring(decodeStr.length() / 2, decodeStr.length()) + decodeStr.substring(0, decodeStr.length() / 2);
            return decodeStr;
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return null;
        }
    }


    public static String substring(String string, int length, String symbol) {
        if (!Validation.isEmpty(string)) {
            try {
                byte[] bytes = string.getBytes("Unicode");
                int n = 0;// 表示当前的字节数
                int i = 2; // 要截取的字节数，从第3个字节开始
                for (; i < bytes.length && n < length; i++) {// 奇数位置，如3、5、7等，为UCS2编码中两个字节的第二个字节
                    if (i % 2 == 1) {
                        n++;// 在UCS2第二个字节时n加1
                    } else {// 当UCS2编码的第一个字节不等于0时，该UCS2字符为汉字，一个汉字算两个字节
                        if (bytes[i] != 0) {
                            n++;
                        }
                    }
                }
                if (i % 2 == 1) {// 如果i为奇数时，处理成偶数
                    if (bytes[i - 1] != 0) {// 该UCS2字符是汉字时，去掉这个截一半的汉字
                        i = i - 1;// 该UCS2字符是字母或数字，则保留该字符
                    } else {
                        i = i + 1;
                    }
                }
                return new String(bytes, 0, i, "Unicode") + ((bytes.length - i) > 0 ? symbol : "");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return "";
    }

    public static String substring(String string, int length) {
        return substring(string, length, "");
    }

    /**
     * <b>功能:</b>获得字符串的md5串
     *
     * @param string 要加密的串
     * @return 加密后的串    成功<br> null		失败
     */
    public static String getMD5(String string) {
        return Md5Utility.getMD5String(string);
    }

    public static String getMD5(File file) throws IOException {
        return Md5Utility.getFileMD5String(file);
    }

    public static String getMD5_IS_16_BIT(String string, boolean is16bit) {
        String result = getMD5(string);
        return is16bit ? result.substring(7, 23) : result;
    }


    /**
     * <b>功能：</b>返回一个List中随机项组成的List
     *
     * @param list   原始List
     * @param number 新List的大小
     * @return randomlist            随机生成的List
     */
    public static List getRandomList(List list, int number) {
        if (number < list.size()) {
            if (number < list.size() / 2) {
                List randomList = new ArrayList();
                int index;
                for (int i = 0; i < number; i++) {
                    index = (int) (Math.random() * (list.size() - 1));
                    randomList.add(list.get(index));
                    list.remove(index);
                }
                return randomList;
            } else {
                while (list.size() > number) {
                    int index = (int) (Math.random() * (list.size() - 1));
                    list.remove(index);
                }
                return list;
            }
        }
        return list;
    }


    /*32未UUID*/

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }

    /*获得随即生成的字符串*/

    public static Integer getRandom(int value) {
        if (value == 0) return 1;
        value = (int) (Math.random() * value);
        return (value == 0) ? 1 : value;
    }

    /*图片压缩辅助方法*/

    public static String getTempFilePath(String... args) {
        if (args.length == 1) {
            StringBuffer buffer = new StringBuffer(args[0]);
            buffer.insert(buffer.toString().indexOf("."), "_temp");
            return buffer.toString();
        } else if (args.length == 2) {
            return args[1];
        }
        return args[0];
    }

    public static String filterHtml(String strBuffer) {
        return strBuffer.replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll(" ", "&nbsp;").replaceAll("\n", "<br>");
    }

    public static String clearHtml(String strBuffer) {
        return filterHtml(strBuffer.replaceAll("</?[^<>]*>", "").replaceAll("\n", "").replaceAll("\r", "").replaceAll(" ", "").replaceAll("&nbsp;", "").replaceAll("　", ""));
    }

    private static Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");

    public static String encode(String str, String charset) {
        StringBuffer b = new StringBuffer();
        try {
            Matcher m = p.matcher(str);
            while (m.find()) {
                m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
            }
            m.appendTail(b);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return b.toString();
    }

    public static String escape(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16) tmp.append("0");
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }

    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }

    public static void ClearSquidCache(String urlhref) {
        try {
            Runtime.getRuntime().exec("squidclient -m PURGE -p 80 " + urlhref);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 由日期(格式MMDD)算出星座并返回字符串
     *
     * @param mmdd
     * @return
     */
    public static String getConstellation(Integer mmdd) {
        if (mmdd <= 119 || mmdd >= 1222) return "摩羯";
        else if (mmdd <= 218 && mmdd >= 120) return "水瓶";
        else if (mmdd <= 320 && mmdd >= 219) return "双鱼";
        else if (mmdd <= 420 && mmdd >= 321) return "牧羊";
        else if (mmdd <= 520 && mmdd >= 421) return "金牛";
        else if (mmdd <= 621 && mmdd >= 521) return "双子";
        else if (mmdd <= 722 && mmdd >= 622) return "巨蟹";
        else if (mmdd <= 822 && mmdd >= 723) return "狮子";
        else if (mmdd <= 922 && mmdd >= 823) return "处女";
        else if (mmdd <= 1022 && mmdd >= 923) return "天秤";
        else if (mmdd < 1121 && mmdd >= 1023) return "天蝎";
        else if (mmdd < 1221 && mmdd >= 1122) return "射手";
        return "";
    }


    /**
     * 图片压缩
     *
     * @param maxWidth
     * @param maxHeight
     * @param fileParms
     * @return
     * @throws Exception
     */
    public static String getConvertImage(int maxWidth, int maxHeight, int x, int y, String... fileParms) throws Exception {
        //TestImageMagick.resizeImg(fileParms[0], getTempFilePath(fileParms), maxWidth, maxHeight, x, y);
        return getTempFilePath(fileParms);
    }


    /**
     * 获取目前时间
     *
     * @return
     */
    public static Date getCurrentDate() {
        return new Date();
    }

    public static String getCurrentDate(String format, int date) {
        return DataFormat.DateFormtString(format, getCurrentDate(date));
    }

    public static Date getCurrentDate(int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, date);
        return calendar.getTime();
    }

    /**
     * 生成字段 username-> Username*
     *
     * @param field
     * @return
     */
    public static String upperCaseFirstCase(String field) {
        //field = field.toLowerCase();
        return field.substring(0, 1).toUpperCase() + field.substring(1, field.length());
    }

    public static Date getFileLastModify(String filepath) {
        return new Date(new File(filepath).lastModified());
    }

    public static String getFileSizeZh(String filepath) {
        return DataFormat.getByteCNM(new File(filepath).length());
    }

    public static Long getFileSize(String filepath) {
        return new File(filepath).length();
    }


    /**
     * <b>功能：</b>测试用, 执行 count次   Runnable.run
     *
     * @param run   执行逻辑
     * @param count 执行次数
     * @return void
     */
    /*测试方法*/
    public static void test(Runnable run, int count) {
        long apptime = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            long start = System.currentTimeMillis();
            run.run();
            System.out.println("第" + i + "次执行耗时:" + (System.currentTimeMillis() - start));
        }
        apptime = (System.currentTimeMillis() - apptime);
        System.out.println("执行" + count + "次总耗时:" + apptime + ",平均耗时:" + (apptime / count));
    }

    public static String getUnicodeString(String temp) {
        StringBuffer tempSb = new StringBuffer();
        try {
            Process p = Runtime.getRuntime().exec("D:\\J2EETOOLS\\JDK1.6\\bin\\native2ascii.exe " + temp);
            InputStreamReader child_in = new InputStreamReader(p.getInputStream());
            int c;
            while ((c = child_in.read()) != -1) {
                tempSb.append((char) c);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return tempSb.toString();

    }

    /*URL编码*/

    public static String url(String url) {
        try {
            return url.replaceAll("\\+", "-srcskya").replaceAll("\\s", "-srcskyb").replaceAll("\\_", "-srcskyc");
            //return URLEncoder.encode(url, "UTF-8");
        } catch (Exception ex) {
            return url;
        }
    }

    public static String[] mergeArray(String[] string, String str) {
        if (!Validation.isEmpty(string)) {
            List<String> list = new ArrayList();
            for (int i = 0; i < string.length; i++) {
                if (!list.contains(string[i]) && Validation.isNotEmpty(string[i])) {
                    list.add(string[i]);
                }
            }
            if (!list.contains(str) && Validation.isNotEmpty(str)) {
                list.add(str);
            }
            return list.toArray(new String[]{});
        } else {
            return new String[]{str};
        }
    }

    public static Integer and(int a, int b) {
        return a & b;
    }

    public static Integer or(int a, int b) {
        return a | b;
    }

    public static String converArrayToString(Object[] objects) {
        return Arrays.toString(objects).replaceAll("\\[|\\|\\,|\\]|\\s", "");
    }

    public String getGreeting() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour >= 6 && hour < 8) {
            return "早上";
        } else if (hour >= 8 && hour < 11) {
            return "上午";
        } else if (hour >= 11 && hour < 13) {
            return "中午";
        } else if (hour >= 13 && hour < 18) {
            return "下午";
        } else {
            return "晚上";
        }
    }

    public static List coverList(Collection collection) {
        /*Arrays.asList(collection.toArray());*/
        List values = new ArrayList();
        values.addAll(collection);
        return values;
    }

    public static void main(String[] args) throws Exception {
        /*coverList(new HashMap().keySet());
        System.out.println(getCurrentDate("yyy", 87 * 60 * 24 * 365));*/
        Map map = new HashMap();
        for (int i = 0; i < 100; i++) {
            String key = System.currentTimeMillis() + "";
            Thread.sleep(2);
            if (map.containsKey(key)) {
                System.out.println(key);
            } else {
                map.put(key, key);
            }
        }
    }
}
